package com.zdy.im.user.facade;

import com.sixeco.framework.common.data.BasePage;
import com.sixeco.framework.common.enums.SysResultCodeEnum;
import com.sixeco.framework.common.enums.TbStatusEnum;
import com.sixeco.framework.core.db.IterableConverter;
import com.sixeco.framework.core.redis.RedisClusterServer;
import com.sixeco.framework.core.redis.RedisKeys;
import com.sixeco.framework.core.redis.RedisUtil;
import com.sixeco.framework.http.data.vo.ResponseResultList;
import com.sixeco.framework.http.exception.SystemRuntimeException;
import com.sixeco.framework.util.crypt.SignParam;
import com.sixeco.framework.util.json.JsonUtils;
import com.zdy.im.conf.ImServerSettings;
import com.zdy.im.enums.ImResultCodeEnum;
import com.zdy.im.user.ImErrorMsg;
import com.zdy.im.user.dto.response.ImRoomUserShipResponseDto;
import com.zdy.im.user.dto.response.ImUserFriendShipResponseDto;
import com.zdy.im.user.dto.response.ImUserGroupInfoResponseDto;
import com.zdy.im.user.dto.response.UserInfoResponseDto;
import com.zdy.im.user.service.*;
import com.zdy.im.user.vo.request.*;
import com.zdy.im.user.dto.request.ImJoinFriendStatusRequestDto;
import com.zdy.im.user.dto.request.ImUserFriendShipRequestDto;
import com.zdy.im.user.dto.request.ImUserGroupInfoRequestDto;
import com.zdy.im.user.dto.request.UserInfoRequestDto;
import com.zdy.im.user.vo.response.LoginImResponseVo;
import com.zdy.im.user.vo.response.UserInfoSearchResponseVo;
import com.zdy.im.user.vo.response.UserLoginImResponseVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**   
 * @Title: UserInfoFacade.java
 * @Author 作者 : zdy
 * @CreateDate 创建时间: 2021-02-30
 * @version V1.0  
 *  <pre>
 * 修改记录
 *    修改后版本:     修改人：  修改日期:     修改内容:
 * </pre>
 * @Description: TODO(说明) 对象缓存统一模板实现类;  
 */
 
@Component
public class UserInfoFacade {

	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private ImUserFriendShipService imUserFriendShipService;
	@Autowired
	private ImUserGroupInfoService imUserGroupInfoService;
	@Autowired
	private ImJoinFriendService imJoinFriendService;
	@Autowired
	private ImServerSettings imServerSettings;
	@Autowired
	private ImRoomUserShipService imRoomUserShipService;
	@Autowired
	private RedisClusterServer redisClusterServer;

	public boolean register(RegisterRequestVo registerRequestVo){
		//判断该用户是否存在
		if(!userInfoService.getByLoginName(registerRequestVo.getName())){
			throw new SystemRuntimeException(SysResultCodeEnum.SYS_USER_REGISTER_FAIL);
		}

		//注册用户
		String finalSecret = "{bcrypt}" + new BCryptPasswordEncoder().encode(registerRequestVo.getPassword().trim());
		UserInfoRequestDto userInfoRequestDto = UserInfoRequestDto.build()
				.toUserName(registerRequestVo.getName())
				.toLoginName(registerRequestVo.getName())
				.toMobile(registerRequestVo.getPhone())
				.toPassword(finalSecret)//BCryptPasswordEncoder方法采用SHA-256 +随机盐+密钥对密码进行加密
				.toHeadImg(imServerSettings.getDefHeadImg())
				.toStatus(TbStatusEnum.ENABLE.index());
		UserInfoResponseDto userInfoResponseDto = userInfoService.saveUserInfo(userInfoRequestDto);
		if(userInfoResponseDto == null){
			throw new SystemRuntimeException(SysResultCodeEnum.SYS_USER_SAVE_FAIL);
		}
		//创建默认好友组
		ImUserGroupInfoRequestDto imUserGroupInfoRequestDto = ImUserGroupInfoRequestDto.build()
				.toGroupName("我的好友")
				.toUserId(userInfoResponseDto.getId())
				.toSort(0)
				.toStatus(TbStatusEnum.ENABLE.index());
		ImUserGroupInfoResponseDto imUserGroupInfoResponseDto = imUserGroupInfoService.saveImUserGroupInfo(imUserGroupInfoRequestDto);

		//创建好友与组关系
		ImUserFriendShipRequestDto imUserFriendShipRequestDto = ImUserFriendShipRequestDto.build()
				.toUserId(userInfoResponseDto.getId())
				.toFriendId(userInfoResponseDto.getId())
				.toUserGroupName(imUserGroupInfoResponseDto.getGroupName())
				.toUserGroupId(imUserGroupInfoResponseDto.getId())
				.toSort(0)
				.toStatus(TbStatusEnum.ENABLE.index())
				.toFriendRemarks(userInfoResponseDto.getUserName());
		imUserFriendShipService.saveImUserFriendShip(imUserFriendShipRequestDto);

		return true;
	}

	/**
	 * 删除好友
	 * @param delFriendVo
	 * @return
	 */
	public boolean delFriend( DelFriendRequestVo delFriendVo){
		ImUserFriendShipResponseDto userFriendShipDto = imUserFriendShipService.selectFriend(delFriendVo.getUserId(), delFriendVo.getFriendId());
		if(userFriendShipDto == null){
			throw new SystemRuntimeException(ImResultCodeEnum.IM_USER_NOT_EXIST);
		}
		/*List<Long> ids = new ArrayList<>();
		ids.add(userFriendShipDto.getId());
		return imUserFriendShipService.delImUserFriendShipByIds(ids);*/
		userFriendShipDto.setStatus(TbStatusEnum.DISABLE.index());
		boolean re =  imUserFriendShipService.updateImUserFriendShip(ImUserFriendShipRequestDto.build().clone(userFriendShipDto));
		if(re){
			String formKey = RedisUtil.formatKey(RedisKeys.MQ_CONSUMER, delFriendVo.getUserId());
			redisClusterServer.hdel(formKey, String.valueOf(delFriendVo.getFriendId()));
			String userKey = RedisUtil.formatKey(RedisKeys.MQ_CONSUMER, delFriendVo.getFriendId());
			redisClusterServer.hdel(userKey, String.valueOf(delFriendVo.getUserId()));
		}
		return re;
	}

	public ResponseResultList<UserInfoSearchResponseVo>  searchUser(UserInfoSearchRequestVo searchRequestVo){
		if (null == searchRequestVo  ){
			throw new SystemRuntimeException(SysResultCodeEnum.SYS_PARAM_ERROR.formatMsg(ImErrorMsg.User.SEARCH_COMTENT_NULL));
		}
		BasePage page =  BasePage.build().toPageSize(searchRequestVo.getPageSize()).toPageNo(searchRequestVo.getPageNo());
		if(null != searchRequestVo.getSearchContent()){
			page.setParamObject(searchRequestVo.getSearchContent());
		}
		List<UserInfoResponseDto>  list = userInfoService.queryUserPageBySearch( page );
		ResponseResultList<UserInfoSearchResponseVo> responseResultList = ResponseResultList.build();
		if(null == list ){
			list = new ArrayList<>();
		}
		boolean isNext =  page.getRealPageSize() == list.size();
		List<UserInfoSearchResponseVo> voList = IterableConverter.convertList(list, UserInfoSearchResponseVo.class);
		responseResultList.toIsNextPage(isNext).toList(voList);
		return responseResultList;
	}

	/**
	 * 修改好友备注
	 * @param friendVo
	 * @return
	 */
	public boolean upFriendRemark( FriendRequestVo friendVo){
		ImUserFriendShipResponseDto userFriendShipDto = imUserFriendShipService.selectFriend(friendVo.getUserId(), friendVo.getFriendId());
		if(userFriendShipDto == null){
			return false;
		}
		userFriendShipDto.setFriendRemarks(friendVo.getFriendRemarks());//修改好友备注
		return imUserFriendShipService.updateImUserFriendShip(ImUserFriendShipRequestDto.build().clone(userFriendShipDto));
	}

	/**
	 * 添加好友
	 * @param friendVo
	 * @return
	 */
	public boolean saveUserFriend( GroupFriendRequestVo friendVo){
		ImUserFriendShipResponseDto userFriendShipDto = imUserFriendShipService.selectFriend(friendVo.getUserId(), friendVo.getFriendId());
		if(userFriendShipDto != null){
			return false;
		}
		//查询用户存不存在
		UserInfoResponseDto userInfoResponseDto = userInfoService.getUserInfoById(friendVo.getUserId());
		if (null == userInfoResponseDto){
			throw new SystemRuntimeException(SysResultCodeEnum.SYS_PARAM_ERROR.formatMsg(ImErrorMsg.User.USER_FRIDEND_NULL));
		}

		//查询好友存不存在
		UserInfoResponseDto userFriendInfoResponseDto = userInfoService.getUserInfoById(friendVo.getFriendId());
		if (null == userFriendInfoResponseDto){
			throw new SystemRuntimeException(SysResultCodeEnum.SYS_PARAM_ERROR.formatMsg(ImErrorMsg.User.FRIEND_FRIDEND_NULL));
		}

		ImUserGroupInfoResponseDto imUserGroupInfoResponseDto = null;
		if(friendVo.getGroupId() > 0){
			//判断该组，是不是该用户
			imUserGroupInfoResponseDto = imUserGroupInfoService.getImUserGroupInfoById(friendVo.getGroupId());//.selectDefGroupOne(friendVo.getUserId());
			if(imUserGroupInfoResponseDto == null || imUserGroupInfoResponseDto.getUserId() != friendVo.getUserId()){
				throw new SystemRuntimeException(SysResultCodeEnum.SYS_PARAM_ERROR.formatMsg(ImErrorMsg.User.USER_GROUP_NULL));
			}
		}
		//默认组
		else{
			//获取默认组
			imUserGroupInfoResponseDto = imUserGroupInfoService.selectDefGroupOne(friendVo.getUserId());
			if(imUserGroupInfoResponseDto == null ){
				throw new SystemRuntimeException(SysResultCodeEnum.SYS_PARAM_ERROR.formatMsg(ImErrorMsg.User.USER_GROUP_NOT_NULL));
			}
		}

		//双绑定操作

		//1.好友与用户关系操作
		//获取好友默认组
		ImUserGroupInfoResponseDto imFriendGroupInfo = imUserGroupInfoService.selectDefGroupOne(friendVo.getFriendId());
		if(imFriendGroupInfo == null ){
			throw new SystemRuntimeException(SysResultCodeEnum.SYS_PARAM_ERROR.formatMsg(ImErrorMsg.User.USER_GROUP_NOT_NULL));
		}
		//获取好友，分组的最大排序sort
		ImUserFriendShipResponseDto imFriendShip = imUserFriendShipService.selectOneByUserIdAndGroupId( friendVo.getFriendId(), imFriendGroupInfo.getId());
		int fridensort = 0;
		if(imFriendShip != null){
			fridensort = imFriendShip.getSort() + 1;
		}
		//创建好友与用户组关系
		ImUserFriendShipRequestDto imFriendShipRequestDto = ImUserFriendShipRequestDto.build()
				.toUserId(friendVo.getFriendId())
				.toFriendId(friendVo.getUserId())
				.toUserGroupName(imFriendGroupInfo.getGroupName())
				.toUserGroupId(imFriendGroupInfo.getId())
				.toSort(fridensort)
				.toStatus(TbStatusEnum.ENABLE.index())
				.toRemarks(friendVo.getRemarks())//备注
				.toFriendRemarks(userInfoResponseDto.getUserName());//好友备注名
		imUserFriendShipService.saveImUserFriendShip(imFriendShipRequestDto);

		//修改好友申请状态
		ImJoinFriendStatusRequestDto imJoinFriendStatus = ImJoinFriendStatusRequestDto.build();
		imJoinFriendStatus
				.toJoinStatus(1)//0.申请 1.同意  2.拒绝,3.删除
				.toSendUserId(friendVo.getFriendId())//好友
				.toToId(friendVo.getUserId());//用户
		imJoinFriendService.updateImJoinFriendStatus ( imJoinFriendStatus);

		//2.用户与好友关系操作
		//获取某个用户，分组的最大排序sort
		ImUserFriendShipResponseDto imUserFriendShip = imUserFriendShipService.selectOneByUserIdAndGroupId( friendVo.getUserId(), imUserGroupInfoResponseDto.getId());
		int sort = 0;
		if(imUserFriendShip != null){
			sort = imUserFriendShip.getSort() + 1;
		}
		//创建好友与组关系
		ImUserFriendShipRequestDto imUserFriendShipRequestDto = ImUserFriendShipRequestDto.build()
				.toUserId(friendVo.getUserId())
				.toFriendId(friendVo.getFriendId())
				.toUserGroupName(imUserGroupInfoResponseDto.getGroupName())
				.toUserGroupId(imUserGroupInfoResponseDto.getId())
				.toSort(sort)
				.toStatus(TbStatusEnum.ENABLE.index())
				.toRemarks(friendVo.getRemarks())//备注
				.toFriendRemarks(userFriendInfoResponseDto.getUserName());//好友备注名
		ImUserFriendShipResponseDto imUserFriendShipResponseDto = imUserFriendShipService.saveImUserFriendShip(imUserFriendShipRequestDto);
		if(imUserFriendShipResponseDto == null){
			return false;
		}
		return true;
	}

	/**
	 * 好友迁移其他组
	 * @param friendVo
	 * @return
	 */
	public boolean userTransferGroup( GroupFriendRequestVo friendVo){
		//查询是否添加好友
		ImUserFriendShipResponseDto userFriendShipDto = imUserFriendShipService.selectFriend(friendVo.getUserId(), friendVo.getFriendId());
		if(userFriendShipDto == null){
			throw new SystemRuntimeException(SysResultCodeEnum.SYS_PARAM_ERROR.formatMsg(ImErrorMsg.User.USER_FRIDEND_NULL));
		}
		//查询好友存不存在
		UserInfoResponseDto userFriendInfoResponseDto = userInfoService.getUserInfoById(friendVo.getFriendId());
		if (null == userFriendInfoResponseDto){
			throw new SystemRuntimeException(SysResultCodeEnum.SYS_PARAM_ERROR.formatMsg(ImErrorMsg.User.USER_FRIDEND_NULL));
		}

		//判断该组，是不是该用户
		ImUserGroupInfoResponseDto imUserGroupInfoResponseDto = imUserGroupInfoService.getImUserGroupInfoById(friendVo.getGroupId());//.selectDefGroupOne(friendVo.getUserId());
		if(imUserGroupInfoResponseDto == null || imUserGroupInfoResponseDto.getUserId() != friendVo.getUserId()){
			throw new SystemRuntimeException(SysResultCodeEnum.SYS_PARAM_ERROR.formatMsg(ImErrorMsg.User.USER_GROUP_NULL));
		}

		//获取某个用户，分组的最大排序sort
		ImUserFriendShipResponseDto imUserFriendShip = imUserFriendShipService.selectOneByUserIdAndGroupId( friendVo.getUserId(), imUserGroupInfoResponseDto.getId());
		int sort = 0;
		if(imUserFriendShip != null){

			sort = imUserFriendShip.getSort();
		}
		//修改好友与组关系
		ImUserFriendShipRequestDto imUserFriendShipRequestDto = ImUserFriendShipRequestDto.build().clone(userFriendShipDto);
		imUserFriendShipRequestDto.toSort(sort+1);//排序
		return imUserFriendShipService.updateImUserFriendShip(imUserFriendShipRequestDto);
	}



	/**
	 * 组合登陆im服务的握手协议实现方法
	 * @param userLoginImRequestVo
	 * @return UserLoginImResponseVo
	 */
	public UserLoginImResponseVo getUserLoginImWsUrl( UserLoginImRequestVo userLoginImRequestVo){
		UserLoginImResponseVo vo = UserLoginImResponseVo.build();
		LoginImResponseVo loginIm = LoginImResponseVo.build().clone(userLoginImRequestVo);
		//todo 查看用户信息;
		//todo 查看用户群查;//目前写死1,2群
		List<Long> roomIdList = new ArrayList<>();//Arrays.asList(1L,2L);
		List<ImRoomUserShipResponseDto> roomUsers = imRoomUserShipService.selectListByUserId(userLoginImRequestVo.getUserId());
		if(!CollectionUtils.isEmpty(roomUsers)){
			roomUsers.forEach(e->{
				roomIdList.add(e.getRoomId());
			});
		}

		loginIm.setUserGroupList(roomIdList);
		loginIm.setCmd("1");//握手协议为1
		Map paramMap = JsonUtils.objectToMap(loginIm);
		String paramUrl = SignParam.getServerSignParam(paramMap,null);
		String wsUrl = imServerSettings.getWs() +"?"+paramUrl;
		vo.setWsUrl(wsUrl);
		return vo;
	}

	/**
	 * 修改用户头像
	 * @param userVo
	 * @return
	 */
	public boolean upHeadImg( UserHeadImgRequestVo userVo){
		UserInfoResponseDto userInfoResponseDto = userInfoService.getUserInfoById(userVo.getUserId());
		if(userInfoResponseDto == null){
			throw new SystemRuntimeException(ImResultCodeEnum.IM_USER_NOT_EXIST);
		}
		userInfoResponseDto.setHeadImg(userVo.getHeadImg());//修改头像
		return userInfoService.updateUserInfo(UserInfoRequestDto.build().clone(userInfoResponseDto));
	}

	/**
	 * 修改用户信息
	 * @param userVo
	 * @return
	 */
	public boolean upUserInfo( UpUserInfoRequestVo userVo){
		UserInfoResponseDto userInfoResponseDto = userInfoService.getUserInfoById(userVo.getUserId());
		if(userInfoResponseDto == null){
			throw new SystemRuntimeException(ImResultCodeEnum.IM_USER_NOT_EXIST);
		}
		userInfoResponseDto
				.toUserName(userVo.getUserName())
				.toEmail(userVo.getEmail())
				.toMobile(userVo.getMobile())
				.toRemarks(userVo.getRemarks());
		if(StringUtils.isNotEmpty(userVo.getHeadImg())){
			userInfoResponseDto.toHeadImg(userVo.getHeadImg());//修改头像
		}

		return userInfoService.updateUserInfo(UserInfoRequestDto.build().clone(userInfoResponseDto));
	}
}
